# coding:utf-8
import sys
from PySide6.QtCore import Qt, QTimer, QUrl, QByteArray, Slot
from PySide6.QtGui import QPixmap, QPainter, QColor, QIcon
from PySide6.QtWidgets import QWidget, QApplication, QHBoxLayout, QVBoxLayout, QStackedWidget
from PySide6.QtNetwork import QNetworkAccessManager, QNetworkRequest, QNetworkReply
import json

from qfluentwidgets import (MSFluentTitleBar, isDarkTheme, ImageLabel, BodyLabel, LineEdit,
                            PasswordLineEdit, PrimaryPushButton, HyperlinkButton, CheckBox, InfoBar,
                            InfoBarPosition, setThemeColor, Pivot, FluentIcon as FIF)
from ..common import resource
from ..common.config import cfg
from ..common.setting import API_URL



def isWin11():
    return sys.platform == 'win32' and sys.getwindowsversion().build >= 22000


if isWin11():
    from qframelesswindow import AcrylicWindow as Window
else:
    from qframelesswindow import FramelessWindow as Window


class LoginInterface(QWidget):
    """ 登录界面 """

    def __init__(self, parent=None):
        super().__init__(parent=parent)

        self.emailLabel = BodyLabel(self.tr('邮箱'), self)
        self.emailLineEdit = LineEdit(self)

        self.passwordLabel = BodyLabel(self.tr('密码'))
        self.passwordLineEdit = PasswordLineEdit(self)

        self.rememberCheckBox = CheckBox(self.tr('记住我'), self)
        self.autoLoginCheckBox = CheckBox(self.tr('自动登录'), self)

        self.loginButton = PrimaryPushButton(self.tr('登录'), self)

        self.vBoxLayout = QVBoxLayout(self)
        self.__initWidgets()

    def __initWidgets(self):
        self.rememberCheckBox.setChecked(cfg.get(cfg.rememberMe))
        self.autoLoginCheckBox.setChecked(cfg.get(cfg.autoLogin))

        self.emailLineEdit.setPlaceholderText('example@example.com')
        self.passwordLineEdit.setPlaceholderText('••••••••••••')

        if self.rememberCheckBox.isChecked():
            self.emailLineEdit.setText(cfg.get(cfg.email))
            self.passwordLineEdit.setText(cfg.get(cfg.password))

        self.__connectSignalToSlot()
        self.__initLayout()

    def __initLayout(self):
        self.vBoxLayout.setContentsMargins(0, 0, 0, 0)
        self.vBoxLayout.setSpacing(0)

        # 创建水平布局用于放置"记住我"和"自动登录"
        self.checkBoxLayout = QHBoxLayout()
        self.checkBoxLayout.addWidget(self.rememberCheckBox)
        self.checkBoxLayout.addStretch(1) # 添加弹性空间，将"自动登录"推到右边
        self.checkBoxLayout.addWidget(self.autoLoginCheckBox)

        self.vBoxLayout.addStretch(1)
        self.vBoxLayout.addWidget(self.emailLabel)
        self.vBoxLayout.addSpacing(11)
        self.vBoxLayout.addWidget(self.emailLineEdit)
        self.vBoxLayout.addSpacing(12)
        self.vBoxLayout.addWidget(self.passwordLabel)
        self.vBoxLayout.addSpacing(11)
        self.vBoxLayout.addWidget(self.passwordLineEdit)
        self.vBoxLayout.addSpacing(12)
        self.vBoxLayout.addLayout(self.checkBoxLayout) # 添加新的水平布局
        self.vBoxLayout.addSpacing(15)
        self.vBoxLayout.addWidget(self.loginButton)
        self.vBoxLayout.addStretch(1)

    def __connectSignalToSlot(self):
        self.rememberCheckBox.stateChanged.connect(
            lambda: cfg.set(cfg.rememberMe, self.rememberCheckBox.isChecked()))
        self.autoLoginCheckBox.stateChanged.connect(self._handle_auto_login_checked)

    def _handle_auto_login_checked(self, state):
        if state == Qt.Checked:
            self.rememberCheckBox.setChecked(True)
            cfg.set(cfg.autoLogin, True)
        else:
            cfg.set(cfg.autoLogin, False)
            cfg.set(cfg.jwtToken, "")


class RegisterInterface(QWidget):
    """ 注册界面 """

    def __init__(self, parent=None):
        super().__init__(parent=parent)
        
        self.emailLabel = BodyLabel(self.tr('邮箱'), self)
        self.emailLineEdit = LineEdit(self)
        
        self.verifyCodeLabel = BodyLabel(self.tr('验证码'))
        self.verifyCodeLineEdit = LineEdit(self)
        self.sendCodeButton = PrimaryPushButton(self.tr('发送验证码'), self)
        
        self.passwordLabel = BodyLabel(self.tr('密码'))
        self.passwordLineEdit = PasswordLineEdit(self)
        
        self.registerButton = PrimaryPushButton(self.tr('注册'), self)

        # 用于发送验证码倒计时
        self.send_code_timer = QTimer(self)
        self.send_code_timer.timeout.connect(self._update_send_code_button_text)
        self.send_code_countdown = 0
        
        self.vBoxLayout = QVBoxLayout(self)
        self.verifyCodeLayout = QHBoxLayout()
        self.__initWidgets()

    def __initWidgets(self):
        self.emailLineEdit.setPlaceholderText('example@example.com')
        self.verifyCodeLineEdit.setPlaceholderText('请输入验证码')
        self.passwordLineEdit.setPlaceholderText('••••••••••••')
        
        self.__connectSignalToSlot()
        self.__initLayout()

    def _update_send_code_button_text(self):
        if self.send_code_countdown > 0:
            self.send_code_countdown -= 1
            self.sendCodeButton.setText(self.tr(f'{self.send_code_countdown}秒后重发'))
            self.sendCodeButton.setEnabled(False)
        else:
            self.send_code_timer.stop()
            self.sendCodeButton.setText(self.tr('发送验证码'))
            self.sendCodeButton.setEnabled(True)

    def __connectSignalToSlot(self):
        self.sendCodeButton.clicked.connect(self._send_verification_code)
        self.registerButton.clicked.connect(self._register_user)

    def _send_verification_code(self):
        email = self.emailLineEdit.text().strip()
        if not email:
            InfoBar.warning(self.tr('提示'), self.tr('请输入邮箱地址'), position=InfoBarPosition.TOP, duration=2000, parent=self.window())
            return

        self.sendCodeButton.setEnabled(False)
        url = QUrl(API_URL + "/user/send-verification-code")
        req = QNetworkRequest(url)
        req.setHeader(QNetworkRequest.ContentTypeHeader, "application/json")

        data_to_send = {
            "email": email,
            "action_type": "REGISTER"
        }
        json_data = QByteArray(json.dumps(data_to_send).encode('utf-8'))

        reply = self.window().network_manager.post(req, json_data)
        reply.finished.connect(lambda: self._handle_send_code_response(reply))

    def _handle_send_code_response(self, reply: QNetworkReply):
        try:
            response_data_bytes = reply.readAll()

            if reply.error() == QNetworkReply.NoError:
                try:
                    json_response = json.loads(response_data_bytes.data().decode('utf-8'))
                except json.JSONDecodeError as e:
                    InfoBar.error(self.tr('处理错误'), self.tr(f'解析响应时出错: {str(e)}'), position=InfoBarPosition.TOP, duration=3000, parent=self.window())
                    self.sendCodeButton.setEnabled(True)
                    return

                if json_response.get("status") == "success":
                    InfoBar.success(self.tr('发送成功'), self.tr('验证码已发送到您的邮箱'), position=InfoBarPosition.TOP, duration=2000, parent=self.window())
                    self.send_code_countdown = 60  # 开始60秒倒计时
                    self._update_send_code_button_text()
                    self.send_code_timer.start(1000) # 每秒触发一次
                else:
                    message = json_response.get("message", "发送验证码失败")
                    InfoBar.error(self.tr('发送失败'), self.tr(message), position=InfoBarPosition.TOP, duration=3000, parent=self.window())
                    self.sendCodeButton.setEnabled(True)
            else:
                # Network or other QNetworkReply error
                qt_error_string = reply.errorString()
                server_message = None
                if response_data_bytes:
                    try:
                        json_error_response = json.loads(response_data_bytes.data().decode('utf-8'))
                        if isinstance(json_error_response, dict) and "message" in json_error_response:
                            server_message = json_error_response["message"]
                    except json.JSONDecodeError:
                        pass # server_message remains None
                
                display_message = server_message if server_message else qt_error_string
                error_title = self.tr("发送失败") if server_message else self.tr("网络错误")

                InfoBar.error(error_title, self.tr(display_message), position=InfoBarPosition.TOP, duration=3000, parent=self.window())
                self.sendCodeButton.setEnabled(True)
        except Exception as e:
            InfoBar.error(self.tr('处理错误'), self.tr(f'解析响应时出错: {str(e)}'), position=InfoBarPosition.TOP, duration=3000, parent=self.window())
            self.sendCodeButton.setEnabled(True)
        finally:
            reply.deleteLater()

    def _register_user(self):
        email = self.emailLineEdit.text().strip()
        password = self.passwordLineEdit.text().strip()
        code = self.verifyCodeLineEdit.text().strip()

        if not email or not password or not code:
            InfoBar.warning(self.tr('提示'), self.tr('邮箱、密码和验证码均不能为空'), position=InfoBarPosition.TOP, duration=2000, parent=self.window())
            return

        if len(password) < 6:
            InfoBar.warning(self.tr('提示'), self.tr('密码长度不能少于6位'), position=InfoBarPosition.TOP, duration=2000, parent=self.window())
            return

        self.registerButton.setEnabled(False)

        url = QUrl(API_URL + "/user/register")
        req = QNetworkRequest(url)
        req.setHeader(QNetworkRequest.ContentTypeHeader, "application/json")

        data_to_send = {
            "email": email,
            "password": password,
            "code": code
        }
        json_data = QByteArray(json.dumps(data_to_send).encode('utf-8'))

        reply = self.window().network_manager.post(req, json_data)
        reply.finished.connect(lambda: self._handle_register_response(reply))

    def _handle_register_response(self, reply: QNetworkReply):
        self.registerButton.setEnabled(True)
        try:
            response_data_bytes = reply.readAll()

            if reply.error() == QNetworkReply.NoError:
                try:
                    json_response = json.loads(response_data_bytes.data().decode('utf-8'))
                except json.JSONDecodeError as e:
                    InfoBar.error(self.tr('处理错误'), self.tr(f'解析响应时出错: {str(e)}'), position=InfoBarPosition.TOP, duration=3000, parent=self.window())
                    return

                if json_response.get("status") == "success":
                    InfoBar.success(self.tr('注册成功'), self.tr('您现在可以登录了'), position=InfoBarPosition.TOP, duration=2000, parent=self.window())
                    self.window().pivot.setCurrentItem("loginInterface")
                else:
                    message = json_response.get("message", "注册失败")
                    InfoBar.error(self.tr('注册失败'), self.tr(message), position=InfoBarPosition.TOP, duration=3000, parent=self.window())
            else:
                # Network or other QNetworkReply error
                qt_error_string = reply.errorString()
                server_message = None
                if response_data_bytes:
                    try:
                        json_error_response = json.loads(response_data_bytes.data().decode('utf-8'))
                        if isinstance(json_error_response, dict) and "message" in json_error_response:
                            server_message = json_error_response["message"]
                    except json.JSONDecodeError:
                        pass # server_message remains None
                
                display_message = server_message if server_message else qt_error_string
                error_title = self.tr("注册失败") if server_message else self.tr("网络错误")

                InfoBar.error(error_title, self.tr(display_message), position=InfoBarPosition.TOP, duration=3000, parent=self.window())
        except Exception as e:
            InfoBar.error(self.tr('处理错误'), self.tr(f'解析响应时出错: {str(e)}'), position=InfoBarPosition.TOP, duration=3000, parent=self.window())
        finally:
            reply.deleteLater()

    def __initLayout(self):
        self.vBoxLayout.setContentsMargins(0, 0, 0, 0)
        self.vBoxLayout.setSpacing(0)
        
        # 验证码输入框和发送按钮的水平布局
        self.verifyCodeLayout.addWidget(self.verifyCodeLineEdit)
        self.verifyCodeLayout.addWidget(self.sendCodeButton)

        self.vBoxLayout.addStretch(1)
        self.vBoxLayout.addWidget(self.emailLabel)
        self.vBoxLayout.addSpacing(11)
        self.vBoxLayout.addWidget(self.emailLineEdit)
        self.vBoxLayout.addSpacing(12)
        self.vBoxLayout.addWidget(self.verifyCodeLabel)
        self.vBoxLayout.addSpacing(11)
        self.vBoxLayout.addLayout(self.verifyCodeLayout)
        self.vBoxLayout.addSpacing(12)
        self.vBoxLayout.addWidget(self.passwordLabel)
        self.vBoxLayout.addSpacing(11)
        self.vBoxLayout.addWidget(self.passwordLineEdit)
        self.vBoxLayout.addSpacing(15)
        self.vBoxLayout.addWidget(self.registerButton)
        self.vBoxLayout.addStretch(1)


class ResetPasswordInterface(QWidget):
    """ 找回密码界面 """

    def __init__(self, parent=None):
        super().__init__(parent=parent)
        
        self.emailLabel = BodyLabel(self.tr('邮箱'), self)
        self.emailLineEdit = LineEdit(self)
        
        self.verifyCodeLabel = BodyLabel(self.tr('验证码'))
        self.verifyCodeLineEdit = LineEdit(self)
        self.sendCodeButton = PrimaryPushButton(self.tr('发送验证码'), self)
        
        self.newPasswordLabel = BodyLabel(self.tr('新密码'))
        self.newPasswordLineEdit = PasswordLineEdit(self)
        
        self.resetButton = PrimaryPushButton(self.tr('重置密码'), self)
        
        self.vBoxLayout = QVBoxLayout(self)
        self.verifyCodeLayout = QHBoxLayout()

        # 用于发送验证码倒计时
        self.send_code_timer = QTimer(self)
        self.send_code_timer.timeout.connect(self._update_send_code_button_text)
        self.send_code_countdown = 0

        self.__initWidgets()

    def __initWidgets(self):
        self.emailLineEdit.setPlaceholderText('example@example.com')
        self.verifyCodeLineEdit.setPlaceholderText('请输入验证码')
        self.newPasswordLineEdit.setPlaceholderText('••••••••••••')
        
        self.__connectSignalToSlot()
        self.__initLayout()

    def _update_send_code_button_text(self):
        if self.send_code_countdown > 0:
            self.send_code_countdown -= 1
            self.sendCodeButton.setText(self.tr(f'{self.send_code_countdown}秒后重发'))
            self.sendCodeButton.setEnabled(False)
        else:
            self.send_code_timer.stop()
            self.sendCodeButton.setText(self.tr('发送验证码'))
            self.sendCodeButton.setEnabled(True)

    def __connectSignalToSlot(self):
        self.sendCodeButton.clicked.connect(self._send_verification_code)
        self.resetButton.clicked.connect(self._reset_password)

    def _send_verification_code(self):
        email = self.emailLineEdit.text().strip()
        if not email:
            InfoBar.warning(self.tr('提示'), self.tr('请输入邮箱地址'), position=InfoBarPosition.TOP, duration=2000, parent=self.window())
            return
        
        self.sendCodeButton.setEnabled(False)
        url = QUrl(API_URL + "/user/send-verification-code")
        req = QNetworkRequest(url)
        req.setHeader(QNetworkRequest.ContentTypeHeader, "application/json")

        data_to_send = {
            "email": email,
            "action_type": "RESET_PASSWORD"
        }
        json_data = QByteArray(json.dumps(data_to_send).encode('utf-8'))

        reply = self.window().network_manager.post(req, json_data)
        reply.finished.connect(lambda: self._handle_send_code_response(reply))

    def _handle_send_code_response(self, reply: QNetworkReply):
        try:
            response_data_bytes = reply.readAll()

            if reply.error() == QNetworkReply.NoError:
                try:
                    json_response = json.loads(response_data_bytes.data().decode('utf-8'))
                except json.JSONDecodeError as e:
                    InfoBar.error(self.tr('处理错误'), self.tr(f'解析响应时出错: {str(e)}'), position=InfoBarPosition.TOP, duration=3000, parent=self.window())
                    self.sendCodeButton.setEnabled(True)
                    return

                if json_response.get("status") == "success":
                    InfoBar.success(self.tr('发送成功'), self.tr('验证码已发送到您的邮箱'), position=InfoBarPosition.TOP, duration=2000, parent=self.window())
                    self.send_code_countdown = 60  # 开始60秒倒计时
                    self._update_send_code_button_text()
                    self.send_code_timer.start(1000) # 每秒触发一次
                else:
                    message = json_response.get("message", "发送验证码失败")
                    InfoBar.error(self.tr('发送失败'), self.tr(message), position=InfoBarPosition.TOP, duration=3000, parent=self.window())
                    self.sendCodeButton.setEnabled(True)
            else:
                # Network or other QNetworkReply error
                qt_error_string = reply.errorString()
                server_message = None
                if response_data_bytes:
                    try:
                        json_error_response = json.loads(response_data_bytes.data().decode('utf-8'))
                        if isinstance(json_error_response, dict) and "message" in json_error_response:
                            server_message = json_error_response["message"]
                    except json.JSONDecodeError:
                        pass # server_message remains None
                
                display_message = server_message if server_message else qt_error_string
                error_title = self.tr("发送失败") if server_message else self.tr("网络错误")

                InfoBar.error(error_title, self.tr(display_message), position=InfoBarPosition.TOP, duration=3000, parent=self.window())
                self.sendCodeButton.setEnabled(True)
        except Exception as e:
            InfoBar.error(self.tr('处理错误'), self.tr(f'解析响应时出错: {str(e)}'), position=InfoBarPosition.TOP, duration=3000, parent=self.window())
            self.sendCodeButton.setEnabled(True)
        finally:
            reply.deleteLater()

    def _reset_password(self):
        email = self.emailLineEdit.text().strip()
        new_password = self.newPasswordLineEdit.text().strip()
        code = self.verifyCodeLineEdit.text().strip()

        if not email or not new_password or not code:
            InfoBar.warning(self.tr('提示'), self.tr('邮箱、新密码和验证码均不能为空'), position=InfoBarPosition.TOP, duration=2000, parent=self.window())
            return

        if len(new_password) < 6:
            InfoBar.warning(self.tr('提示'), self.tr('新密码长度不能少于6位'), position=InfoBarPosition.TOP, duration=2000, parent=self.window())
            return

        self.resetButton.setEnabled(False)

        url = QUrl(API_URL + "/user/reset-password")
        req = QNetworkRequest(url)
        req.setHeader(QNetworkRequest.ContentTypeHeader, "application/json")

        data_to_send = {
            "email": email,
            "password": new_password,
            "code": code
        }
        json_data = QByteArray(json.dumps(data_to_send).encode('utf-8'))

        reply = self.window().network_manager.post(req, json_data)
        reply.finished.connect(lambda: self._handle_reset_password_response(reply))

    def _handle_reset_password_response(self, reply: QNetworkReply):
        self.resetButton.setEnabled(True)
        try:
            response_data_bytes = reply.readAll()

            if reply.error() == QNetworkReply.NoError:
                try:
                    json_response = json.loads(response_data_bytes.data().decode('utf-8'))
                except json.JSONDecodeError as e:
                    InfoBar.error(self.tr('处理错误'), self.tr(f'解析响应时出错: {str(e)}'), position=InfoBarPosition.TOP, duration=3000, parent=self.window())
                    return
                
                if json_response.get("status") == "success":
                    InfoBar.success(self.tr('重置成功'), self.tr('您的密码已重置，请使用新密码登录'), position=InfoBarPosition.TOP, duration=2000, parent=self.window())
                    self.window().pivot.setCurrentItem("loginInterface")
                else:
                    message = json_response.get("message", "密码重置失败")
                    InfoBar.error(self.tr('重置失败'), self.tr(message), position=InfoBarPosition.TOP, duration=3000, parent=self.window())
            else:
                # Network or other QNetworkReply error
                qt_error_string = reply.errorString()
                server_message = None
                if response_data_bytes:
                    try:
                        json_error_response = json.loads(response_data_bytes.data().decode('utf-8'))
                        if isinstance(json_error_response, dict) and "message" in json_error_response:
                            server_message = json_error_response["message"]
                    except json.JSONDecodeError:
                        pass # server_message remains None
                
                display_message = server_message if server_message else qt_error_string
                error_title = self.tr("重置失败") if server_message else self.tr("网络错误")

                InfoBar.error(error_title, self.tr(display_message), position=InfoBarPosition.TOP, duration=3000, parent=self.window())
        except Exception as e:
            InfoBar.error(self.tr('处理错误'), self.tr(f'解析响应时出错: {str(e)}'), position=InfoBarPosition.TOP, duration=3000, parent=self.window())
        finally:
            reply.deleteLater()

    def __initLayout(self):
        self.vBoxLayout.setContentsMargins(0, 0, 0, 0)
        self.vBoxLayout.setSpacing(0)
        
        # 验证码输入框和发送按钮的水平布局
        self.verifyCodeLayout.addWidget(self.verifyCodeLineEdit)
        self.verifyCodeLayout.addWidget(self.sendCodeButton)

        self.vBoxLayout.addStretch(1)
        self.vBoxLayout.addWidget(self.emailLabel)
        self.vBoxLayout.addSpacing(11)
        self.vBoxLayout.addWidget(self.emailLineEdit)
        self.vBoxLayout.addSpacing(12)
        self.vBoxLayout.addWidget(self.verifyCodeLabel)
        self.vBoxLayout.addSpacing(11)
        self.vBoxLayout.addLayout(self.verifyCodeLayout)
        self.vBoxLayout.addSpacing(12)
        self.vBoxLayout.addWidget(self.newPasswordLabel)
        self.vBoxLayout.addSpacing(11)
        self.vBoxLayout.addWidget(self.newPasswordLineEdit)
        self.vBoxLayout.addSpacing(15)
        self.vBoxLayout.addWidget(self.resetButton)
        self.vBoxLayout.addStretch(1)


class AuthWindow(Window):
    """ 认证窗口: 包含登录、注册和找回密码功能 """

    def __init__(self, parent=None):
        super().__init__(parent=parent)
        setThemeColor('#28afe9')
        self.setTitleBar(MSFluentTitleBar(self))
        
        self.network_manager = QNetworkAccessManager(self)
        self.jwt_token = None  # 新增：用于存储JWT
        
        self.imageLabel = ImageLabel(':/app/images/background.jpg', self)
        self.iconLabel = ImageLabel(':/app/images/logo.png', self)

        # 创建Pivot和QStackedWidget
        self.pivot = Pivot(self)
        self.stackedWidget = QStackedWidget(self)
        
        # 创建各个功能界面
        self.loginInterface = LoginInterface(self)
        self.registerInterface = RegisterInterface(self)
        self.resetPasswordInterface = ResetPasswordInterface(self)
        
        self.hBoxLayout = QHBoxLayout(self)
        self.rightPanelLayout = QVBoxLayout()

        self.__initWidgets()

    def __initWidgets(self):
        self.titleBar.maxBtn.hide()
        self.titleBar.setDoubleClickEnabled(False)

        # 添加子界面到Pivot和QStackedWidget
        self.addSubInterface(self.loginInterface, 'loginInterface', '登录', FIF.EMBED)
        self.addSubInterface(self.registerInterface, 'registerInterface', '注册', FIF.PEOPLE)
        self.addSubInterface(self.resetPasswordInterface, 'resetPasswordInterface', '找回密码', FIF.HELP)

        self.__connectSignalToSlot()
        self.__initLayout()

        if isWin11():
            self.windowEffect.setMicaEffect(self.winId(), isDarkTheme())
        else:
            color = QColor(25, 33, 42) if isDarkTheme() else QColor(240, 244, 249)
            self.setStyleSheet(f"AuthWindow{{background: {color.name()}}}")
        
        self.setWindowTitle('智拓AI')
        self.setWindowIcon(QIcon(":/app/images/logo.png"))
        self.resize(1000, 650)

        self.titleBar.titleLabel.setStyleSheet("""
            QLabel{
                background: transparent;
                font: 13px 'Segoe UI';
                padding: 0 4px;
                color: white
            }
        """)

        desktop = QApplication.screens()[0].availableGeometry()
        w, h = desktop.width(), desktop.height()
        self.move(w//2 - self.width()//2, h//2 - self.height()//2)

        self.titleBar.raise_()
        
        # 默认选中登录界面
        self.pivot.setCurrentItem("loginInterface")

        # 尝试自动登录, 确保在父窗口等都初始化完毕后进行
        QTimer.singleShot(0, self._tryAutoLogin) 

    def addSubInterface(self, widget, objectName, text, icon):
        """ 添加子界面到Pivot和QStackedWidget """
        widget.setObjectName(objectName)
        self.stackedWidget.addWidget(widget)
        self.pivot.addItem(routeKey=objectName, text=text, icon=icon)

    def __initLayout(self):
        self.imageLabel.scaledToHeight(650)
        self.iconLabel.scaledToHeight(100)

        self.hBoxLayout.addWidget(self.imageLabel)
        self.hBoxLayout.addLayout(self.rightPanelLayout)

        self.hBoxLayout.setContentsMargins(0, 0, 0, 0)
        self.rightPanelLayout.setContentsMargins(20, 0, 20, 0)
        self.rightPanelLayout.setSpacing(0)
        self.hBoxLayout.setSpacing(0)

        self.rightPanelLayout.addStretch(1)
        self.rightPanelLayout.addWidget(
            self.iconLabel, 0, Qt.AlignmentFlag.AlignHCenter)
        self.rightPanelLayout.addSpacing(20)
        self.rightPanelLayout.addWidget(self.pivot)
        self.rightPanelLayout.addSpacing(10)
        self.rightPanelLayout.addWidget(self.stackedWidget)
        self.rightPanelLayout.addSpacing(30)
        self.rightPanelLayout.addStretch(1)

    def __connectSignalToSlot(self):
        # 连接Pivot的currentItemChanged信号到QStackedWidget的切换
        self.pivot.currentItemChanged.connect(
            lambda k: self.stackedWidget.setCurrentWidget(self.findChild(QWidget, k)))
        
        # 连接登录按钮的点击信号
        self.loginInterface.loginButton.clicked.connect(self._login)

    def _tryAutoLogin(self):
        if cfg.get(cfg.autoLogin) and cfg.get(cfg.jwtToken):
            # 禁用登录界面的交互，防止用户在自动登录过程中进行操作
            self.loginInterface.setEnabled(False)
            self.registerInterface.setEnabled(False)
            self.resetPasswordInterface.setEnabled(False)
            self.pivot.setEnabled(False)

            self.jwt_token = cfg.get(cfg.jwtToken)

            # 延迟执行，确保窗口切换和提示信息显示更流畅
            QTimer.singleShot(100, lambda: self._proceed_auto_login_success())

    def _proceed_auto_login_success(self):
        InfoBar.success(
            self.tr("自动登录成功"),
            self.tr('欢迎回来'),
            position=InfoBarPosition.TOP,
            duration=1500, # 调整时长
            parent=self # 确保InfoBar在此窗口显示
        )
        # 再次延迟以确保InfoBar有足够时间显示
        QTimer.singleShot(1600, self._showMainWindow)

    def _login(self):
        code = self.loginInterface.passwordLineEdit.text().strip()
        email = self.loginInterface.emailLineEdit.text().strip()

        if not email or not code:
            InfoBar.error(
                self.tr("登录失败"),
                self.tr('邮箱和密码不能为空'),
                position=InfoBarPosition.TOP,
                duration=2000,
                parent=self.window()
            )
            return

        if len(code) < 6:
            InfoBar.warning(
                self.tr("登录失败"),
                self.tr('密码长度不能少于6位'),
                position=InfoBarPosition.TOP,
                duration=2000,
                parent=self.window()
            )
            return

        self.loginInterface.loginButton.setEnabled(False)

        url = QUrl(API_URL + "/user/login")
        req = QNetworkRequest(url)
        req.setHeader(QNetworkRequest.ContentTypeHeader, "application/json")

        data_to_send = {
            "email": email,
            "password": code
        }
        
        json_data = QByteArray(json.dumps(data_to_send).encode('utf-8'))

        reply = self.network_manager.post(req, json_data)
        reply.finished.connect(lambda: self._handle_login_response(reply, email, code))

    def _handle_login_response(self, reply: QNetworkReply, email, password_or_code):
        self.loginInterface.loginButton.setEnabled(True)
        try:
            response_data_bytes = reply.readAll()

            if reply.error() == QNetworkReply.NoError:
                try:
                    json_response = json.loads(response_data_bytes.data().decode('utf-8'))
                except json.JSONDecodeError as e:
                    InfoBar.error(
                        self.tr("解析错误"),
                        self.tr(f"无法解析服务器响应: {str(e)}"),
                        position=InfoBarPosition.TOP,
                        duration=3000,
                        parent=self.window()
                    )
                    return

                if json_response.get("status") == "success":
                    InfoBar.success(
                        self.tr("登录成功"),
                        self.tr('欢迎回来'),
                        position=InfoBarPosition.TOP,
                        parent=self.window()
                    )

                    if self.loginInterface.rememberCheckBox.isChecked():
                        cfg.set(cfg.email, email)
                        cfg.set(cfg.password, password_or_code)
                    else:
                        cfg.set(cfg.email, "")
                        cfg.set(cfg.password, "")

                    self.jwt_token = json_response.get("token") # 保存JWT
                    cfg.set(cfg.jwtToken, self.jwt_token)
                    if self.loginInterface.autoLoginCheckBox.isChecked():
                        cfg.set(cfg.autoLogin, True)
                        
                    else:
                        cfg.set(cfg.autoLogin, False)

                    self.loginInterface.loginButton.setDisabled(True)
                    QTimer.singleShot(1500, self._showMainWindow)
                else:
                    message = json_response.get("message", "登录失败，请检查您的凭据")
                    InfoBar.error(
                        self.tr("登录失败"),
                        self.tr(message),
                        position=InfoBarPosition.TOP,
                        duration=3000,
                        parent=self.window()
                    )
            else:
                # Network or other QNetworkReply error
                qt_error_string = reply.errorString()
                server_message = None
                if response_data_bytes:
                    try:
                        json_error_response = json.loads(response_data_bytes.data().decode('utf-8'))
                        if isinstance(json_error_response, dict) and "message" in json_error_response:
                            server_message = json_error_response["message"]
                    except json.JSONDecodeError:
                        pass # server_message remains None
                
                display_message = server_message if server_message else qt_error_string
                error_title = self.tr("登录失败") if server_message else self.tr("网络错误")
                
                InfoBar.error(
                    error_title,
                    self.tr(display_message),
                    position=InfoBarPosition.TOP,
                    duration=3000,
                    parent=self.window()
                )
        except Exception as e:
            InfoBar.error(
                self.tr("处理错误"),
                self.tr(f"解析响应时出错: {str(e)}"),
                position=InfoBarPosition.TOP,
                duration=3000,
                parent=self.window()
            )
        finally:
            reply.deleteLater()

    def _showMainWindow(self):
        self.close()
        setThemeColor('#009faa')

        # 在需要时导入，避免循环导入
        from .main_window import MainWindow
        w = MainWindow() # 传递JWT
        w.show()

# 导出AuthWindow作为模块的主类
RegisterWindow = AuthWindow
